package com.block.api.controller.sys;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.block.applet.service.AppletConfigInfoService;
import com.block.applet.service.AppletCountInfoService;
import com.block.channel.service.IChannelBaseInfoService;
import com.block.common.bean.SessionBean;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.exception.ApiException;
import com.block.common.security.util.ApiUtil;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.ISystemConstantInfoService;
import com.block.common.util.IpUtil;
import com.block.common.util.LocalDateUtil;
import com.block.common.vo.ResponseVo;
import com.block.db.entity.*;
import com.block.product.service.IProductBaseInfoService;
import com.block.product.service.IProductOnlieInfoService;
import com.block.test.service.IMiniPageJumpInfoService;
import com.block.test.service.IWxEventCountService;
import com.block.tool.service.IToolsNewsInfoService;
import com.market.member.service.IMemberAreacityPositionService;
import com.market.member.service.IMemberLoginSessionService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("api/sys")
@Validated
public class SysController {

    @Autowired
    IProductOnlieInfoService productOnlieInfoService;

    @Autowired
    AppletConfigInfoService appletConfigInfoService;

    @Autowired
    IWxEventCountService wxEventCountService;

    @Autowired
    IMiniPageJumpInfoService miniPageJumpInfoService;
    @Autowired
    ISystemConstantInfoService systemConstantInfoService;
    @Autowired
    IProductBaseInfoService productBaseInfoService;

    @Autowired
    IMemberLoginSessionService  memberLoginSessionService;
    @Autowired
    IApplicationInfoService  applicationInfoService;
    @Autowired
    AppletCountInfoService appletCountInfoService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;



    /**
     * api/sys/gzhPageJumpInfo
     * 获取最新的新闻列表
     */
    @RequestMapping(value = "/gzhPageJumpInfo", method = {RequestMethod.POST, RequestMethod.GET})
    public String gzhPageJumpInfo(@RequestAttribute(value = "tranData") JSONObject tranData,
                              @RequestAttribute(value = "appEncrypt") AppEncrypt appEncrypt,
                                @RequestAttribute(value = "channelBaseInfo") ChannelBaseInfo channelBaseInfo,
                                @RequestAttribute(value = "applicationInfo") ApplicationInfo applicationInfo,
                                @RequestAttribute(value = "uri") String uri,
                                @RequestAttribute(value = "startDate") Date startdate,
                                @RequestAttribute(value = "ip") String ip) throws ApiException {

        JSONObject jsonObject = new JSONObject();
        String type = tranData.getString("type");
        AppletConfigInfo appletConfigInfo = appletConfigInfoService.selectAppletByChannelCode(channelBaseInfo.getChannelCode());
        if (type != null) {
            if (appletConfigInfo.getGzhStatus() == 0) {
                ResponseVo responseVo = new ResponseVo(AppRspCodeConstant.SUCCESS);
                return ApiUtil.dealReturnJson(responseVo, appEncrypt, startdate, uri);
            }
        }
            jsonObject.put("gzhLogo", appletConfigInfo.getGzhLogo());
            jsonObject.put("gzhName", appletConfigInfo.getGzhName());
            jsonObject.put("gzhQrCode", appletConfigInfo.getGzhQrCode());
            ResponseVo responseVo = new ResponseVo(AppRspCodeConstant.SUCCESS, jsonObject);
            return ApiUtil.dealReturnJson(responseVo, appEncrypt, startdate, uri);

    }

    @RequestMapping(value = "/weCom", method = {RequestMethod.POST, RequestMethod.GET})
    public String weCom(HttpServletRequest request,
            @RequestAttribute(value = "tranData") JSONObject tranData,
            @RequestAttribute(value = "appEncrypt") AppEncrypt appEncrypt,
            @RequestAttribute(value = "channelBaseInfo") ChannelBaseInfo channelBaseInfo,
            @RequestAttribute(value = "applicationInfo") ApplicationInfo applicationInfo,
            @RequestAttribute(value = "uri") String uri,
            @RequestAttribute(value = "startDate") Date startdate,
            @RequestAttribute(value = "ip") String ip) throws ApiException {

        JSONObject jsonObject = new JSONObject();
        String token = tranData.getString("token");
        String uuid = token.substring(token.lastIndexOf("::") + 2);
        String nowDate = LocalDate.now().toString();
        Long uid = memberLoginSessionService.getUidByToken(uuid,nowDate);
        List<ProductOnlieInfo> productOnlieInfo = productOnlieInfoService.getWeCom(uid,channelBaseInfo);
        if(ObjectUtil.isNotEmpty(productOnlieInfo)) {
            String reqIp = IpUtil.getIp(request);
            String redisKey = StrUtil.format(RedisKeyConstant.COUNT_UV_COM_KEY, channelBaseInfo.getChannelCode(), reqIp);
            boolean result = stringRedisTemplate.opsForValue()
                    .setIfAbsent(redisKey, System.currentTimeMillis() + "", LocalDateUtil.getRemainSecondNumber(), TimeUnit.SECONDS);
            if(result) {
                appletCountInfoService.insertWxCount(channelBaseInfo.getChannelCode(), uid.toString(), "4");
            }
            ProductOnlieInfo onlieInfo = productOnlieInfo.get(0);
            ProductBaseInfo productBaseInfo = productBaseInfoService.getProductInfoById(onlieInfo.getProductId());
            jsonObject.put("gzhLogo", productBaseInfo.getLogoUrl());
            jsonObject.put("gzhName", productBaseInfo.getProductName());
            jsonObject.put("gzhQrCode", productBaseInfo.getBackgroundLogo());
            jsonObject.put("type", 1);
            ResponseVo responseVo = new ResponseVo(AppRspCodeConstant.SUCCESS, jsonObject);
            return ApiUtil.dealReturnJson(responseVo, appEncrypt, startdate, uri);
        }
        AppletConfigInfo appletConfigInfo = appletConfigInfoService.selectAppletByChannelCode(channelBaseInfo.getChannelCode());
        jsonObject.put("gzhLogo", appletConfigInfo.getGzhLogo());
        jsonObject.put("gzhName", appletConfigInfo.getGzhName());
        jsonObject.put("gzhQrCode", appletConfigInfo.getGzhQrCode());
        jsonObject.put("type", 0);
        ResponseVo responseVo = new ResponseVo(AppRspCodeConstant.SUCCESS, jsonObject);
        return ApiUtil.dealReturnJson(responseVo, appEncrypt, startdate, uri);
    }



    /**
     * api/sys/wxEventCount
     * userUuid
     * type:1,小程序启动事件;2, 公众号二维码页面进入事件;3,二维码长按事件
     * 小程序事件统计
     */
    @RequestMapping(value = "/wxEventCount", method = {RequestMethod.POST, RequestMethod.GET})
    public String wxEventCount(HttpServletRequest request,
            @RequestAttribute(value = "tranData") JSONObject tranData,
                                  @RequestAttribute(value = "appEncrypt") AppEncrypt appEncrypt,
                                  @RequestAttribute(value = "channelBaseInfo") ChannelBaseInfo channelBaseInfo,
                                  @RequestAttribute(value = "applicationInfo") ApplicationInfo applicationInfo,
                                  @RequestAttribute(value = "uri") String uri,
                                  @RequestAttribute(value = "startDate") Date startdate,
                                  @RequestAttribute(value = "ip") String ip) throws ApiException {

        String userUuid = tranData.getString("userUuid");// 每个用户的随机ID
        String type = tranData.getString("type");// type:1,小程序启动事件;2, 公众号二维码页面进入事件;3,二维码长按事件

        if(tranData.getString("token") == null){
            wxEventCountService.wxEventCountNotToken(channelBaseInfo, userUuid, type, request, userUuid);
        }
         else {
            String token = tranData.getString("token");
            String uuid = token.substring(token.lastIndexOf("::") + 2);
            String nowDate = LocalDate.now().toString();
            Long uid = memberLoginSessionService.getUidByToken(uuid, nowDate);
            wxEventCountService.wxEventCount(channelBaseInfo, userUuid, type, request, uid.toString());
        }
        ResponseVo responseVo = new ResponseVo(AppRspCodeConstant.SUCCESS);
        return ApiUtil.dealReturnJson(responseVo, appEncrypt, startdate, uri);
    }

    @RequestMapping(value = "/appEventCount", method = {RequestMethod.POST, RequestMethod.GET})
    public String appEventCount(HttpServletRequest request,
                                @RequestAttribute(value = "tranData") JSONObject tranData,
                                @RequestAttribute(value = "appEncrypt") AppEncrypt appEncrypt,
                                @RequestAttribute(value = "channelBaseInfo") ChannelBaseInfo channelBaseInfo,
                                @RequestAttribute(value = "applicationInfo") ApplicationInfo applicationInfo,
                                @RequestAttribute(value = "uri") String uri,
                                @RequestAttribute(value = "startDate") Date startdate,
                                @RequestAttribute(value = "ip") String ip) throws ApiException {

        String userUuid = tranData.getString("userUuid");
        wxEventCountService.appEventCount(channelBaseInfo,userUuid,request);
        ResponseVo responseVo = new ResponseVo(AppRspCodeConstant.SUCCESS);
        return ApiUtil.dealReturnJson(responseVo, appEncrypt, startdate, uri);
    }


    /**
     *api/sys/getChannelCode
     * 获取appid绑定的channelCode
     */
    @RequestMapping(value = "/getChannelCode", method = {RequestMethod.POST, RequestMethod.GET})
    public String getChannelCode(@RequestAttribute(value = "tranData") JSONObject tranData,
                               @RequestAttribute(value = "appEncrypt") AppEncrypt appEncrypt,
                               @RequestAttribute(value = "channelBaseInfo") ChannelBaseInfo channelBaseInfo,
                               @RequestAttribute(value = "applicationInfo") ApplicationInfo applicationInfo,
                               @RequestAttribute(value = "uri") String uri,
                               @RequestAttribute(value = "startDate") Date startdate,
                               @RequestAttribute(value = "ip") String ip) throws ApiException {

        String appid = tranData.getString("wxAppid");
        String channelCode = appletConfigInfoService.getChannelCode(appid);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("channelCode", channelCode);


        ResponseVo responseVo = new ResponseVo(AppRspCodeConstant.SUCCESS,jsonObject);
        return ApiUtil.dealReturnJson(responseVo, appEncrypt, startdate, uri);
    }


    @RequestMapping(value = "/miniPageJumpInfo", method = {RequestMethod.POST, RequestMethod.GET})
    public String miniPageJumpInfo(@RequestAttribute(value = "tranData") JSONObject tranData,
                                  @RequestAttribute(value = "appEncrypt") AppEncrypt appEncrypt,
                                  @RequestAttribute(value = "channelBaseInfo") ChannelBaseInfo channelBaseInfo,
                                  @RequestAttribute(value = "applicationInfo") ApplicationInfo applicationInfo,
                                  @RequestAttribute(value = "uri") String uri,
                                  @RequestAttribute(value = "startDate") Date startdate,
                                  @RequestAttribute(value = "ip") String ip) throws ApiException {

        JSONObject jsonObject = miniPageJumpInfoService.miniPageJumpInfo(channelBaseInfo);

        ResponseVo responseVo = new ResponseVo(AppRspCodeConstant.SUCCESS,jsonObject);
        return ApiUtil.dealReturnJson(responseVo, appEncrypt, startdate, uri);

    }

    @RequestMapping(value = "/miniPageJumpH5Info", method = {RequestMethod.POST, RequestMethod.GET})
    public String miniPageJumpH5Info(@RequestAttribute(value = "tranData") JSONObject tranData,
                                   @RequestAttribute(value = "appEncrypt") AppEncrypt appEncrypt,
                                   @RequestAttribute(value = "channelBaseInfo") ChannelBaseInfo channelBaseInfo,
                                   @RequestAttribute(value = "applicationInfo") ApplicationInfo applicationInfo,
                                   @RequestAttribute(value = "uri") String uri,
                                   @RequestAttribute(value = "startDate") Date startdate,
                                   @RequestAttribute(value = "ip") String ip) throws ApiException {

        JSONObject jsonObject = miniPageJumpInfoService.miniPageJumpH5Info(channelBaseInfo);

        ResponseVo responseVo = new ResponseVo(AppRspCodeConstant.SUCCESS,jsonObject);
        return ApiUtil.dealReturnJson(responseVo, appEncrypt, startdate, uri);

    }

    @RequestMapping(value = "/getSystemConstantInfo", method = {RequestMethod.POST, RequestMethod.GET})
    public String getSystem(@RequestAttribute(value = "tranData") JSONObject tranData,
                                   @RequestAttribute(value = "appEncrypt") AppEncrypt appEncrypt,
                                   @RequestAttribute(value = "channelBaseInfo") ChannelBaseInfo channelBaseInfo,
                                   @RequestAttribute(value = "applicationInfo") ApplicationInfo applicationInfo,
                                   @RequestAttribute(value = "uri") String uri,
                                   @RequestAttribute(value = "startDate") Date startdate,
                                   @RequestAttribute(value = "ip") String ip) throws ApiException {

        String id = tranData.getString("id");
        SystemConstantInfo systemConstantInfo = systemConstantInfoService.getSystemByCode(id);
        String name = systemConstantInfo.getName();
        String code = systemConstantInfo.getCode();
        String contentInfo = systemConstantInfo.getContentInfo();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("code", code);
        jsonObject.put("contentInfo", contentInfo);
        ResponseVo responseVo = new ResponseVo(AppRspCodeConstant.SUCCESS,jsonObject);
        return ApiUtil.dealReturnJson(responseVo, appEncrypt, startdate, uri);

    }

    @RequestMapping(value = "/getPage", method = {RequestMethod.POST, RequestMethod.GET})
    public String getPage(@RequestAttribute(value = "tranData") JSONObject tranData,
                            @RequestAttribute(value = "appEncrypt") AppEncrypt appEncrypt,
                            @RequestAttribute(value = "channelBaseInfo") ChannelBaseInfo channelBaseInfo,
                            @RequestAttribute(value = "applicationInfo") ApplicationInfo applicationInfo,
                            @RequestAttribute(value = "uri") String uri,
                            @RequestAttribute(value = "startDate") Date startdate,
                            @RequestAttribute(value = "ip") String ip) throws ApiException {

        //经度

        Boolean status = applicationInfoService.getPage(ip,channelBaseInfo);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", status);
        ResponseVo responseVo = new ResponseVo(AppRspCodeConstant.SUCCESS,jsonObject);
        return ApiUtil.dealReturnJson(responseVo, appEncrypt, startdate, uri);

    }

    @RequestMapping(value = "/sourceInfoByCode", method = {RequestMethod.POST, RequestMethod.GET})
    public String sourceInfoByCode(@RequestAttribute(value = "tranData") JSONObject tranData,
                          @RequestAttribute(value = "appEncrypt") AppEncrypt appEncrypt,
                          @RequestAttribute(value = "channelBaseInfo") ChannelBaseInfo channelBaseInfo,
                          @RequestAttribute(value = "applicationInfo") ApplicationInfo applicationInfo,
                          @RequestAttribute(value = "uri") String uri,
                          @RequestAttribute(value = "startDate") Date startdate,
                          @RequestAttribute(value = "ip") String ip) throws ApiException {

        JSONObject jsonObject = new JSONObject();
//        String yuqi = tranData.getString("yq");
//        Integer age = tranData.getInteger("age");
//        String zhima = tranData.getString("zm");
//
//        MemberSourceInfo memberSourceInfo = new MemberSourceInfo();
//        memberSourceInfo.setYuqi(yuqi);
//        memberSourceInfo.setAge(age);
//        memberSourceInfo.setZhima(zhima);
        MemberSourceInfo memberSourceInfo = new MemberSourceInfo();
        memberSourceInfo.setAge(tranData.getInteger("age"));
        memberSourceInfo.setHouse(tranData.getString("house"));
        memberSourceInfo.setLoanAmount(tranData.getString("loan_amount"));
        memberSourceInfo.setZhima(tranData.getString("zhima"));
        memberSourceInfo.setXueli(tranData.getString("xueli"));
        memberSourceInfo.setGongzuo(tranData.getString("gongzuo"));
        memberSourceInfo.setYuqi(tranData.getString("yuqi"));
        memberSourceInfo.setShouru(tranData.getString("shouru"));
        memberSourceInfo.setHouse(tranData.getString("house"));
        memberSourceInfo.setCar(tranData.getString("car"));
        memberSourceInfo.setGjj(tranData.getString("gjj"));
        memberSourceInfo.setShebao(tranData.getString("shebao"));
        memberSourceInfo.setBaoxian(tranData.getString("baoxian"));
        memberSourceInfo.setHuabei(tranData.getString("huabei"));
        memberSourceInfo.setBaitiao(tranData.getString("baitiao"));
        List<ProductOnlieInfo> productOnlieInfo = productOnlieInfoService.getWeCom1(memberSourceInfo,channelBaseInfo);
        if(ObjectUtil.isNotEmpty(productOnlieInfo)) {
            ProductOnlieInfo onlieInfo = productOnlieInfo.get(0);
            ProductBaseInfo productBaseInfo = productBaseInfoService.getProductInfoById(onlieInfo.getProductId());
            jsonObject.put("gzhLogo", productBaseInfo.getLogoUrl());
            jsonObject.put("gzhName", productBaseInfo.getProductName());
            jsonObject.put("gzhQrCode", productBaseInfo.getBackgroundLogo());
            ResponseVo responseVo = new ResponseVo(AppRspCodeConstant.SUCCESS, jsonObject);
            return ApiUtil.dealReturnJson(responseVo, appEncrypt, startdate, uri);
        }
        AppletConfigInfo appletConfigInfo = appletConfigInfoService.selectAppletByChannelCode(channelBaseInfo.getChannelCode());
        jsonObject.put("gzhLogo", appletConfigInfo.getGzhLogo());
        jsonObject.put("gzhName", appletConfigInfo.getGzhName());
        jsonObject.put("gzhQrCode", appletConfigInfo.getGzhQrCode());
        ResponseVo responseVo = new ResponseVo(AppRspCodeConstant.SUCCESS, jsonObject);
        return ApiUtil.dealReturnJson(responseVo, appEncrypt, startdate, uri);

    }

}
